package com.jiaai.web.common;
import com.alibaba.dubbo.config.annotation.Reference;
import com.jiaai.common.api.ICodeApi;
import com.jiaai.exception.ServerException;
import com.jiaai.member.api.IMemberApi;
import com.jiaai.util.RestResultGenerator;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author 佳爱网络科技
 * @version V1.0
 * @title CodeConteller
 * @since 2017/10/11
 */
@RestController
@RequestMapping("/api/v1/app/code")
public class CodeConteller {
    @Reference
    private ICodeApi codeApi;
    @Reference(check = false)
    private IMemberApi iMemberApi;

    /**
     * 检查手机号码是否已注册, 是则发送短信
     * @param mobile
     * @return
     */
    @PostMapping("/checkexist")
    public Object checkMobile(@RequestParam String mobile){
        if (!iMemberApi.checkMobile(mobile)){
            return RestResultGenerator.genErrorResult("该手机号码未注册!");
        }else {
            try {
                codeApi.sendCode(mobile);
                return RestResultGenerator.genSuccessResult("已发送");
            } catch (ServerException e) {
                if (e.getMessage().equals("ERRORPHONE")){
                    return RestResultGenerator.genErrorResult("手机号码格式错误!");
                }
                throw new RuntimeException("服务器挂了!");
            }
        }
    }

    /**
     * 发送手机验证码
     * @param mobile
     * @return
     * @throws ServerException
     */
    @PostMapping("/send")
    public  Object sendCode(@RequestParam String mobile)throws ServerException{
        try {
            codeApi.sendCode(mobile);
            return RestResultGenerator.genSuccessResult("已发送");
        }catch (Exception e){
            if (e.getMessage().equals("ERRORPHONE")){
                return RestResultGenerator.genErrorResult("手机号码格式错误!");
            }
            e.printStackTrace();
        }
        throw new RuntimeException("服务器挂了!");
    }

    /**
     * 验证码检测
     * @param mobile
     * @param code
     * @return
     * @throws ServerException
     */
    @GetMapping("/check")
    public  Object checkCode(@RequestParam String mobile,@RequestParam String code)throws ServerException{
        if(codeApi.checkCode(mobile,code)){
            return RestResultGenerator.genSuccessResult("验证码正确");
        }else{
            return  RestResultGenerator.genErrorResult("验证码错误");
        }
    }

}
